package com.janwen.spring.mvc;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MixLayerService {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	private static final Log logger = LogFactory.getLog(MixLayerService.class);

	/**
	 * 不使用@Transactional注解,sql自动提交,使用@Transactional后方法结束才会整体提交
	 * 不使用  type=
	 * janwen
	 * @param username
	 * @param age
	 * @return
	 *
	 */
	@RequestMapping("/mvc/updateUser.do")
	public String updateAge(String username, String age) {
		try {
			jdbcTemplate.execute("INSERT INTO stuff  SET name='yahoo',age=500");
			String sql = "UPDATE stuff sf SET sf.age=? WHERE sf.name=?";
			if (jdbcTemplate.update(sql, age, username) > 0) {
				return "success";
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}

		return "fail";

	}

	/**
	 * 使用@Transactional注解后,每次调用改方法都会新起一个默认事务
	 * transaction.annotation.AnnotationTransactionAttributeSource	(AbstractFallbackTransactionAttributeSource.java:106)	-Adding transactional method 'QueryYahoo' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''

	 * janwen
	 * @param name
	 * @return
	 *
	 */
	@RequestMapping("/mvc/queryUser.do")
	@Transactional
	public String QueryYahoo(String name){
		List results = jdbcTemplate.queryForList("SELECT * FROM stuff st WHERE st.name=?", name);
		logger.info(results.size());
		if(results.size() > 0){
			return "success";
		}
		return "fail";
	}
}
